package com.standardoperationapp.activity;

import java.text.SimpleDateFormat;
import java.util.Calendar;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker.OnTimeChangedListener;

import com.standardoperationapp.R;

public class SelectTimeActivity implements OnDateChangedListener,OnTimeChangedListener{
    private DatePicker datePicker;
    private TimePicker timePicker;
    private AlertDialog ad;
    private String dateTime;
    private long longTime, tmpTime;
    private String sipFormatdt;
    private String initDateTime;
    private Context context;
    private boolean bZeroSecond = true;


    public SelectTimeActivity(Context context,String initDateTime, boolean bZeroSec)
    {
        this.context = context;
        this.initDateTime=initDateTime;
        this.bZeroSecond = bZeroSec;

        Calendar calendar= Calendar.getInstance();
        if(!(null==initDateTime||"".equals(initDateTime)))
        {
            calendar = this.getCalendarByInintData(initDateTime);
        }else
        {
            initDateTime=calendar.get(Calendar.YEAR)+"年"+calendar.get(Calendar.MONTH)+"月"+calendar.get(Calendar.DAY_OF_MONTH)+"日 "+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND);
        }
        int m = calendar.get(Calendar.MONTH) + 1;
        //this.sipFormatdt = calendar.get(Calendar.YEAR)+"-"+m+"-"+calendar.get(Calendar.DAY_OF_MONTH)+" "+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND);
        this.sipFormatdt = String.format("%4d-%02d-%02d %02d:%02d:%02d",
                calendar.get(Calendar.YEAR), m, calendar.get(Calendar.DAY_OF_MONTH),
                calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
        longTime = tmpTime = calendar.getTimeInMillis()/1000;
    }

    public void init(DatePicker datePicker,TimePicker timePicker)
    {
        Calendar calendar= Calendar.getInstance();
        if(!(null==initDateTime||"".equals(initDateTime)))
        {
            calendar = this.getCalendarByInintData(initDateTime);
        }else
        {
            initDateTime=calendar.get(Calendar.YEAR)+"年"+calendar.get(Calendar.MONTH)+"月"+calendar.get(Calendar.DAY_OF_MONTH)+"日 "+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE);
        }

        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH), this);
        timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
        timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE));

    }

    /**
     * 弹出日期时间选择框方法
     * @param inputDate:为需要设置的日期时间文本编辑框
     * @return
     */
    public AlertDialog dateTimePicKDialog(final TextView inputDate)
    {
        LayoutInflater factory = LayoutInflater.from(context);
        LinearLayout dateTimeLayout  = (LinearLayout) factory.inflate(R.layout.selecttime, null);
        datePicker = (DatePicker) dateTimeLayout.findViewById(R.id.select_date);
        timePicker = (TimePicker) dateTimeLayout.findViewById(R.id.select_time);
        datePicker.setClickable(false);
        datePicker.setLongClickable(false);
        //datePicker.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
        timePicker.setIs24HourView(true);
        timePicker.setOnTimeChangedListener(this);
        init(datePicker,timePicker);
        ad = new AlertDialog.Builder(context).setTitle(initDateTime).setView(dateTimeLayout).setPositiveButton("设置",
                new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog,
                                        int whichButton)
                    {
                        onDateChanged(null, 0, 0, 0);
                      //  onTimeChanged(null,0,0);
                        inputDate.setText(dateTime);
                        longTime = tmpTime;
                    }
                }).setNegativeButton("取消",
                new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog,
                                        int whichButton)
                    {
                        //inputDate.setText(dateTime);
                    }
                }).show();

       // onDateChanged(null, 0, 0, 0);
        return ad;
    }


    public void onTimeChanged(TimePicker view, int hourOfDay, int minute)
    {
      //  onDateChanged(null, 0, 0, 0);

    }

    public void onDateChanged(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth)
    {
        Calendar calendar = Calendar.getInstance();

        if (bZeroSecond)
        {
            calendar.set(datePicker.getYear(), datePicker.getMonth(),
                    datePicker.getDayOfMonth(), timePicker.getCurrentHour(),
                    timePicker.getCurrentMinute(), 0);
        }
        else
        {
            calendar.set(datePicker.getYear(), datePicker.getMonth(),
                    datePicker.getDayOfMonth(), timePicker.getCurrentHour(),
                    timePicker.getCurrentMinute(), 59);
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        dateTime=sdf.format(calendar.getTime());
        tmpTime = calendar.getTime().getTime()/1000;

        //SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-ddHH:mm");
        int m = calendar.get(Calendar.MONTH)+1;
		/*sipFormatdt = calendar.get(Calendar.YEAR)
				+"-"+m
				+"-"+calendar.get(Calendar.DAY_OF_MONTH)
				+" "+calendar.get(Calendar.HOUR_OF_DAY)
				+":"+calendar.get(Calendar.MINUTE)
				+":"+calendar.get(Calendar.SECOND);*/
        sipFormatdt = String.format("%4d-%02d-%02d %02d:%02d:%02d",
                calendar.get(Calendar.YEAR), m, calendar.get(Calendar.DAY_OF_MONTH),
                calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
        ad.setTitle(dateTime);
    }

    public String getSipFormatDataTime(){
        return sipFormatdt;
    }

    public long getSecond(){
        return longTime;
    }

    /**
     * 实现将初始日期时间2013年03月02日 16:45 拆分成年 月 日 时 分 秒,并赋值给calendar
     * @param initDateTime 初始日期时间值 字符串型
     * @return Calendar
     */
    private Calendar getCalendarByInintData(String initDateTime) {
        Calendar calendar = Calendar.getInstance();

        // 将初始日期时间2013年03月02日 16:45 拆分成年 月 日 时 分 秒
        String date = spliteString(initDateTime, "日", "index", "front");
        String time = spliteString(initDateTime, "日", "index", "back");

        String yearStr = spliteString(date, "年", "index", "front");
        String monthAndDay = spliteString(date, "年", "index", "back");

        String monthStr = spliteString(monthAndDay, "月", "index","front");
        String dayStr = spliteString(monthAndDay, "月", "index", "back");

        String hourStr = spliteString(time, ":", "index", "front");
        String minuteStr = spliteString(time, ":", "index", "back");
        int currentYear = Integer.valueOf(yearStr.trim()).intValue();
        int currentMonth = Integer.valueOf(monthStr.trim()).intValue() - 1;
        int currentDay = Integer.valueOf(dayStr.trim()).intValue();
        int currentHour = Integer.valueOf(hourStr.trim()).intValue();
        int currentMinute = Integer.valueOf(minuteStr.trim()).intValue();


        if (bZeroSecond)
        {
            calendar.set(currentYear, currentMonth, currentDay, currentHour, currentMinute, 0);
        }
        else
        {
            calendar.set(currentYear, currentMonth, currentDay, currentHour, currentMinute, 59);
        }

        return calendar;
    }

    public static String spliteString(String srcStr,String pattern,String indexOrLast,String frontOrBack)
    {
        String result="";
        int loc=-1;
        if(indexOrLast.equalsIgnoreCase("index"))
        {
            loc=srcStr.indexOf(pattern);
        }else
        {
            loc=srcStr.lastIndexOf(pattern);
        }
        if(frontOrBack.equalsIgnoreCase("front"))
        {
            if(loc!=-1)result=srcStr.substring(0,loc);
        }else
        {
            if(loc!=-1)result=srcStr.substring(loc+1,srcStr.length());
        }
        return result;
    }

    public void finish()
    {
        if(ad != null)
        {
            ad.cancel();
        }
    }

    public void setDateTime(String strCurTime)
    {
        int nPos1  = strCurTime.indexOf(":");
        int nPos2 = strCurTime.indexOf(":", nPos1+1);

        if (-1 == nPos2) // xxxx年xx月xx日 时:分
        {
            this.initDateTime = strCurTime;

        }
        else // xxxx年xx月xx日 时:分:秒
        {
            String strTmp = strCurTime;
            this.initDateTime = strCurTime.substring(0, strCurTime.length()-3);
        }

        //this.initDateTime = strCurTime;
    }
}